import { useEffect, useRef, useState } from 'react'
import './index.scss'
import { UserCircleOutline } from 'antd-mobile-icons'
import { Input } from 'antd';
import {
  SearchOutlined
} from '@ant-design/icons';
import { Swiper } from 'antd-mobile'
import axios from '../../api/index'
import { Tabs } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import dayjs from 'dayjs'

function Home3() {
  const navigate = useNavigate()
  // 轮播图数据
  interface ImgItem {
    imageUrl: string;
  }
  const [img, setImg] = useState<ImgItem[]>([])
  useEffect(() => {
    axios.get('/share/v1/bannersShow').then(res => {
      // console.log(res);
      setImg(res.data.result)
    })
  }, [])
  // 问诊咨询
  interface WzItem {
    id: number;
    pic: string;
    departmentName: string;
  }
  const [wz, setWz] = useState<WzItem[]>([])
  useEffect(() => {
    axios.get('/share/knowledgeBase/v1/findDepartment').then(res => {
      // console.log(res);
      setWz(res.data.result)
    })
  }, [])
  // 健康咨询渲染列表
  interface JkzxItem {
    id: number;
    name: string;
  }
  const [jkzx, setJkzx] = useState<JkzxItem[]>([])
  useEffect(() => {
    axios.get('/share/information/v1/findInformationPlateList').then(res => {
      // console.log(res);
      setJkzx(res.data.result)
    })
  }, [])
  interface JklbItem {
    id: number;
    title: string;
    thumbnail: string;
    source: string;
    releaseTime: string;
  }
  const [jklb, setJklb] = useState<JklbItem[]>([])
  const [plateId, setPlateId] = useState(1)
  const [page, setPage] = useState(1)
  const [count] = useState(1)
  const [loadingMore, setLoadingMore] = useState(false)
  const [hasMore, setHasMore] = useState(true)
  const loadMoreRef = useRef<HTMLDivElement | null>(null)

  // tabbar 状态管理
  const [activeTab, setActiveTab] = useState(0)

  // 公告轮播文字
  const [currentAnnouncementIndex, setCurrentAnnouncementIndex] = useState(0)
  const [isTransitioning, setIsTransitioning] = useState(false)
  const announcements = [
    "智慧医院即将上线通知",
    "系统维护通知：今晚22:00-24:00",
    "新功能上线：在线问诊服务",
    "重要提醒：请及时更新个人信息",
    "医院开放时间调整通知"
  ]
  
  // 创建包含副本的公告数组，用于无缝循环
  const extendedAnnouncements = [...announcements, ...announcements]

  // 切换 tab 重置分页
  useEffect(() => {
    setJklb([])
    setPage(1)
    setHasMore(true)
  }, [plateId])

  // 拉取列表（分页追加）
  useEffect(() => {
    if (!hasMore && page !== 1) return
    setLoadingMore(true)
    axios.get('/share/information/v1/findInformationList', {
      params: { plateId, page, count }
    }).then(res => {
      const list = res?.data?.result || []
      setJklb(prev => page === 1 ? list : ([...prev, ...list]))
      if (Array.isArray(list) && list.length < count) setHasMore(false)
    }).finally(() => setLoadingMore(false))
  }, [plateId, page, count, hasMore])

  // 触底监听
  useEffect(() => {
    if (!loadMoreRef.current) return
    const el = loadMoreRef.current
    const observer = new IntersectionObserver(entries => {
      const first = entries[0]
      if (first.isIntersecting && !loadingMore && hasMore) {
        setPage(p => p + 1)
      }
    })
    observer.observe(el)
    return () => observer.disconnect()
  }, [loadingMore, hasMore])

  // 公告轮播定时器
  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentAnnouncementIndex(prev => {
        const nextIndex = prev + 1
        
        // 当滚动到原始数组的最后一个时，继续滚动到副本
        if (nextIndex === announcements.length) {
          // 继续滚动到副本的第一个（即原始数组的第一个）
          return nextIndex
        }
        
        // 当滚动到副本的最后一个时，无缝重置到原始数组的第一个
        if (nextIndex === extendedAnnouncements.length) {
          // 暂时禁用过渡动画
          setIsTransitioning(true)
          // 立即重置到原始数组的第一个位置
          setTimeout(() => {
            setCurrentAnnouncementIndex(0)
            // 重新启用过渡动画
            setTimeout(() => {
              setIsTransitioning(false)
            }, 50)
          }, 500) // 等待当前动画完成
          return nextIndex
        }
        
        return nextIndex
      })
    }, 2500) // 每2.5秒切换一次，给动画更多时间

    return () => clearInterval(timer)
  }, [announcements.length, extendedAnnouncements.length])
  return (
    <div className='head'>
      {/* 顶部搜索 */}
      <div className='h-top'>
        <div className='h_left'>
          <span className='tb'>
            <UserCircleOutline className='tb' onClick={() => navigate('/login')} />
          </span>
        </div>
        <div className='h_middle'>
          <Input size="large" placeholder="请输入症状疾病" prefix={<SearchOutlined />} className='ss' onClick={() => navigate('/ss')} />
        </div>
        <div className='h_footer'>
          <span >
            <img src="../../../public/15.png" alt="" className='ld' onClick={() => navigate('')} />
          </span>
        </div>
      </div>
      <div className='synr'>
        {/* 轮播图 */}
        <div className='lbt'>
          <Swiper style={{ width: '100%', height: '160px' }} autoplay loop>
            {
              img.map((item, index) => {
                return <Swiper.Item key={index} >
                  <img src={item.imageUrl} alt="" style={{ width: '100%', height: '100%' }} />
                </Swiper.Item>
              })
            }
          </Swiper>
        </div>
        {/* 知识宝典 */}
        <div className='zsbd'>
          <span className='zsbd-title'>知识宝典</span>
        </div>
        <div className='bzyp' onClick={() => navigate('/zsk')}>
          <div className='bz_left' >
            <span className='bzyp-title'>常见病症</span>
            <span><img src="../../../public/16.png" alt="" /></span>
          </div>
          <div className='yp_right'>
            <span className='yp_right-title'>常见药品</span>
            <span><img src="../../../public/17.png" alt="" /></span>
          </div>
        </div>
        {/* 问诊咨询 */}
        <div className='wzzx'>
          <span className='wzzx-title'>问诊咨询</span>
        </div>
        <div className='zxlb' >
          {
            wz.map((item, index) => {
              return <div key={index} onClick={() => navigate(`/ks?deptId=${item.id}`)}>
                <img src={item.pic} alt="" />
                <p>{item.departmentName}</p>
              </div>
            })
          }
        </div>
        {/* 门诊挂号缴费 */}
        <div className='mzkghj'>
          <div className='mzkghj-left' onClick={() => navigate('/yytz')}>
            <div className='mzkghj-left-icon'>
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <rect x="3" y="4" width="18" height="18" rx="2" stroke="white" strokeWidth="2" />
                <line x1="16" y1="2" x2="16" y2="6" stroke="white" strokeWidth="2" />
                <line x1="8" y1="2" x2="8" y2="6" stroke="white" strokeWidth="2" />
                <line x1="3" y1="10" x2="21" y2="10" stroke="white" strokeWidth="2" />
                <path d="M9 14L11 16L15 12" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </div>
            <div className='mzkghj-left-content'>
              <div className='mzkghj-left-title'>门诊挂号</div>
              <div className='mzkghj-left-subtitle'>便捷预约挂号</div>
            </div>
          </div>
          <div className='mzkghj-right'>
            <div className='mzkghj-left-icon'>
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M12 2L2 7L12 12L22 7L12 2Z" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                <path d="M2 17L12 22L22 17" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                <path d="M2 12L12 17L22 12" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </div>
            <div className='mzkghj-left-content'>
              <div className='mzkghj-left-title'>门诊缴费</div>
              <div className='mzkghj-left-subtitle'>便捷预约挂号</div>
            </div>
          </div>
        </div>
        {/* 公告 */}
        <div className='gg'>
          <div className='gg-content'>
            <div className='gg-title'>公告</div>
            <div className='gg-divider'></div>
            <div className='gg-scroll-container'>
              <div 
                className='gg-text-wrapper'
                style={{ 
                  transform: `translateY(-${currentAnnouncementIndex * 100}%)`,
                  transition: isTransitioning ? 'none' : 'transform 0.5s ease-in-out'
                }}
              >
                {extendedAnnouncements.map((announcement, index) => (
                  <div key={index} className='gg-text'>{announcement}</div>
                ))}
              </div>
            </div>
            <div className='gg-arrow'>{'>'}</div>
          </div>
        </div>
        {/* 门诊住院综合 */}
        <div className='mzzyzh'>
          <span className='mzzyzh-title'>门诊住院综合</span>
        </div>
        <div className='mzzyzh-tabbar'>
          <div className='mzzyzh-tabbar-tabs'>
            <div
              className={`tab-item ${activeTab === 0 ? 'active' : ''}`}
              onClick={() => setActiveTab(0)}
            >
              门诊
            </div>
            <div
              className={`tab-item ${activeTab === 1 ? 'active' : ''}`}
              onClick={() => setActiveTab(1)}
            >
              住院
            </div>
            <div
              className={`tab-item ${activeTab === 2 ? 'active' : ''}`}
              onClick={() => setActiveTab(2)}
            >
              综合
            </div>
          </div>
          <div className='mzzyzh-tabbar-more'>
            <span className='more-text' onClick={() => navigate('/caidan')}>更多</span>
          </div>
        </div>

        {/* 根据选中的标签显示不同内容 */}
        <div className='mzzyzh-content'>
          {activeTab === 0 && (
            <div className='outpatient-grid'>
              <div className='service-item' onClick={()=>navigate('/mzbg')}>
                <div className='service-icon'></div>
                <span className='service-text' >门诊报告</span>
              </div>

              <div className='service-item' onClick={()=>navigate('/hzcx')}>
                <div className='service-icon'></div>
                <span className='service-text'>候诊查询</span>
              </div>
              <div className='service-item' onClick={()=>navigate('/zzkd')}>
                <div className='service-icon'></div>
                <span className='service-text'>自助开单</span>
              </div>
              <div className='service-item' onClick={()=>navigate('/yjyy')}>
                <div className='service-icon'></div>
                <span className='service-text'>医技预约</span>
              </div>
              <div className='service-item'>
                <div className='service-icon'></div>
                <span className='service-text'>我的复诊</span>
              </div>
              <div className='service-item'>
                <div className='service-icon'></div>
                <span className='service-text'>自助取号</span>
              </div>
              <div className='service-item'>
                <div className='service-icon'></div>
                <span className='service-text'>门诊导诊台</span>
              </div>
              <div className='service-item'>
                <div className='service-icon'></div>
                <span className='service-text'>电子票据</span>
              </div>
            </div>
          )}
          {activeTab === 1 && <div>
            <div className='outpatient-grid'>
              <div className='service-item' onClick={()=>navigate('/ryqr')}>
                <div className='service-icon'></div>
                <span className='service-text'>入院登记</span>
              </div>
              <div className='service-item'>
                <div className='service-icon'></div>
                <span className='service-text'>住院预交</span>
              </div>
              <div className='service-item'>
                <div className='service-icon'></div>
                <span className='service-text'>住院报告</span>
              </div>
              <div className='service-item'>
                <div className='service-icon'></div>
                <span className='service-text'>住院日清单</span>
              </div>
              <div className='service-item'>
                <div className='service-icon'></div>
                <span className='service-text'>住院陪护证</span>
              </div>
            </div>
          </div>}
          {activeTab === 2 && <div>
            <div className='outpatient-grid'>
              <div className='service-item'>
                <div className='service-icon'></div>
                <span className='service-text'>代寄服务</span>
              </div>
              <div className='service-item'>
                <div className='service-icon'></div>
                <span className='service-text'>中药代煎</span>
              </div>
              <div className='service-item'>
                <div className='service-icon'></div>
                <span className='service-text'>价目查询</span>
              </div>
              <div className='service-item'>
                <div className='service-icon'></div>
                <span className='service-text'>就医指南</span>
              </div>
              <div className='service-item'>
                <div className='service-icon'></div>
                <span className='service-text'>满意度调查</span>
              </div>
              <div className='service-item'>
                <div className='service-icon'></div>
                <span className='service-text'>楼层分布</span>
              </div>
            </div>
          </div>}
        </div>
        {/* 健康查询 */}
        <div className='jkcx'>
            <div className='jkcx-title'>
              <span className='jkcx-title-text'>健康查询</span>
              <span className='jkcx-title-more' onClick={()=>navigate}>更多</span>
            </div>
            <div className='jkcx-content'>
              <div className='jkcx-card'>
                <div className='jkcx-card-content'>
                  <div className='jkcx-card-text'>
                    <h3>世界糖尿病日,应该注意什么来调理?</h3>
                    <div className='jkcx-card-meta'>
                      <span className='jkcx-hashtag'>#健康养生</span>
                      <div className='jkcx-stats'>
                        <span className='jkcx-likes'>👍 520</span>
                        <span className='jkcx-views'>👁 2000</span>
                      </div>
                    </div>
                  </div>
                  <div className='jkcx-card-thumbnail'>
                    <div className='jkcx-placeholder'></div>
                  </div>
                </div>
              </div>
              
              <div className='jkcx-card'>
                <div className='jkcx-card-content'>
                  <div className='jkcx-card-text'>
                    <h3>冬季养生小贴士,如何保持身体健康?</h3>
                    <div className='jkcx-card-meta'>
                      <span className='jkcx-hashtag'>#冬季养生</span>
                      <div className='jkcx-stats'>
                        <span className='jkcx-likes'>👍 380</span>
                        <span className='jkcx-views'>👁 1500</span>
                      </div>
                    </div>
                  </div>
                  <div className='jkcx-card-thumbnail'>
                    <div className='jkcx-placeholder'></div>
                  </div>
                </div>
              </div>
            </div>
        </div>
        {/* 健康评测 */}
        <div className='jkpc'>
          <span className='jkpc-title'>健康评测</span>
        </div>
        <div className='jkpctb'>
          <img src="../../../public/18.png" alt="" />
        </div>
        <div className='jkzx'>
          <span className='jkzx-title'>健康咨询</span>
        </div>
        <div className='jkqk'>
          {/* 健康咨询tab切换以及渲染列表 */}
          <Tabs onChange={(key) => setPlateId(Number(key))}>
            {
              jkzx.map((item) => {
                return <Tabs.Tab key={item.id} title={item.name}>

                </Tabs.Tab>
              })
            }
          </Tabs>
        </div>
        <div className='jklb'>
          {
            jklb.map((item) => {
              return <div key={item.id} className='jklb-item' onClick={() => navigate(`/syxq/${item.id}`)}>
                <img className='thumb' src={item.thumbnail} alt='' />
                <div className='info'>
                  <div className='title'>{item.title}</div>
                  <div className='sjdl'>
                    <div className='dl'>{item.source}</div>
                    <div className='sj'>{dayjs(item.releaseTime).format('YYYY-MM-DD')}</div>
                  </div>

                </div>
              </div>
            })
          }
          {/* 下拉加载 */}
          <div ref={loadMoreRef} style={{ height: 1 }} />
          <div style={{ textAlign: 'center', color: '#999', padding: '8px 0' }}>
            {loadingMore ? '加载中...' : (hasMore ? '下拉加载更多' : '没有更多')}
          </div>
          <div style={{ height: 72 }} />
        </div>
      </div>

      {/* 智能客服按钮 */}
      <div className='smart-customer-service' onClick={() => navigate('/ailt')}>
        <span className='smart-customer-service-text'>智能客服</span>
      </div>

    </div>
  )
}

export default Home3